import React, { useEffect, useState, Suspense, useRef } from 'react'
import { Tag, Modal, Layout, Card, Carousel, message, Avatar, List, Tooltip,Input,InputNumber, Descriptions, Image, Button, Table, Space, Row, Col, Cascader, Drawer, Divider } from 'antd';
import { QuestionCircleTwoTone } from '@ant-design/icons';

import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
import axios from 'axios';
// import { checkLoginState } from '../../../../js/CheckLoginState'
import provinceData from '../../../../js/provinceData';
const { confirm } = Modal;
let donationRs = {};
let allorg = [];
export default function Index() {
  const [loginUser, setLoginUser] = useState(JSON.parse(localStorage.getItem("loginUser")))
  const [listData, setListData] = useState([]);
  const [listDataBac, setListDataBac] = useState([]); //存一份获取的数据用于筛选
  const navigate = useNavigate();
  const [orgDetailDrawer, setOrgDetailDrawer] = useState(false)
  const [currentOrg, setCurrentOrg] = useState(listData[0]);
  const [donationModal, setDonationModal] = useState(false)
  useEffect(async () => {
    const resp = await axios.get("http://localhost:8080/qryOrgList")
    console.log("机构列表及其物资需求:", resp);
    setListData(resp.data.data)
    setListDataBac(resp.data.data)
  }, [])
  const filterCity = (value) => {
    console.log(value);
    if (value) { //如果筛选了 执行
      console.log("baclistdata", listDataBac);
      setListData(listDataBac)
      let rs = "";
      for (let i = 0; i < value.length; i++) {
        rs += value[i];
      }
      console.log("筛选物品:", value);
      console.log("最终筛选物品str", rs);
      const newListData = listDataBac.filter(item => item.city === rs)
      console.log("物品类别筛选后的结果:", newListData);
      setListData(newListData)
    } else { //点击X后就是undefined把备份的listdata赋回去
      setListData(listDataBac)
    }
  }
  const openOrgDetail = (record) => {
    console.log('正在查看的org是:', record)
    setOrgDetailDrawer(true)
    setCurrentOrg(record)

  }
  const openDonation = (record) => {
    setCurrentOrg(record)
    setDonationModal(true)
    donationRs = {}
    donationRs.goods = []

  }
  const donationOk = async () => {
    donationRs.userid = loginUser.id;
    donationRs.orgid = currentOrg.id;
    setDonationModal(false)
    for(let i=donationRs.goods.length-1;i>=0;i--){
      if (donationRs.goods[i].goodsnum ==0) {
        donationRs.goods.splice(i,1)
      }
    }
    console.log(donationRs);
    const resp = await axios.post("http://localhost:8080/userDonation", donationRs)
    message.success("操作成功,可前往历史界面查看!")
    setDonationModal(false)
    setTimeout(() => {
      window.location.reload()
    }, 500);
    
    donationRs =  {}
  }

  const showDetailGoods = (record) => {
    Modal.info({
        title: '详细信息',
        content: <Row>
            {record.goodsneed.map((item, index) => {
                return <Tag color="green">{item.goodsname}</Tag>
            })}
        </Row>,

    });
}
  const columns = [
    {
      title: '机构名称',ellipsis: true,
      render: (text, record) => (
        <Row align='middle'>
          <Col span={8}>
            <Avatar size={'large'} src={`http://localhost:8080/getOrgHead?id=${record.id}`} />
          </Col>
          <Col>{record.orgname}</Col>
        </Row>
      ),
    },
    {
      title: <Cascader  placeholder={"城区"} 
      onChange={filterCity} options={provinceData} />,
      ellipsis: true,
      render: (text, record) => (
        <span style={{ color: 'gray' }}>{record.city}</span>
      )
    },
    {
      title: '详细地址',
      ellipsis: true,
      render: (text, record) => (
        <span style={{ color: 'gray' }}>{record.address}</span>
      )
    },
    {
      title: <Tooltip title="点击查看详情">物资需求 <QuestionCircleTwoTone /></Tooltip>,
      ellipsis: true,
      render: (text, record) => (
        <Space onClick={() => { showDetailGoods(record) }}>
          {record.goodsneed.map((item, index) => {
            return <Tag color="green">{item.goodsname}</Tag>
          })}
        </Space>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => { openDonation(record) }}>捐赠</Button>
          {/* <Button type="primary" onClick={() => { openOrgDetail(record) }}>详细信息</Button> */}
          <Button type="primary" onClick={() => {navigate('/userMenu/orgDetail',{state:record})  }}>详细信息</Button>
        </Space>
      ),
    },
  ];
  return (
    <div className="animate__animated animate__fadeIn">
      <Table columns={columns} dataSource={listData} />
      <Drawer
        title="机构信息"
        placement='bottom'
        width={500}
        onClose={() => { setOrgDetailDrawer(false) }}
        height={'80%'}
        visible={orgDetailDrawer}
      >
        <Row style={{ width: '100%', height: '100%' }}>
          <Col span={10} >
            <Row >
              <Card title={<Avatar size={'large'} src={`http://localhost:8080/getOrgHead?id=${currentOrg?.id}`} />} extra={<span style={{ color: 'gray' }}>{currentOrg?.orgname}</span>} style={{ width: '100%' }}>
                <Descriptions column={1} bordered>
                  <Descriptions.Item label="所在城市">{currentOrg?.city}</Descriptions.Item>
                  <Descriptions.Item label="详细地址">{currentOrg?.address}</Descriptions.Item>
                  <Descriptions.Item label="联系邮箱">{currentOrg?.email}</Descriptions.Item>
                  <Descriptions.Item label="联系电话">{currentOrg?.phone}</Descriptions.Item>
                  <Descriptions.Item label="组织介绍">{currentOrg?.orgmsg}</Descriptions.Item>
                  <Descriptions.Item label="我们需要">
                    {
                      <Space>
                        {
                          currentOrg?.goodsneed.map((item, index) => {
                            return <Tag color="green">{item.goodsname}</Tag>
                          })
                        }
                      </Space>
                    }
                  </Descriptions.Item>
                </Descriptions>
              </Card>
            </Row>
            <Row>
            </Row>
          </Col>
          <Col span={14} style={{ backgroundColor: 'pink' }}>
            <Image.PreviewGroup>
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
              <Image width={'20%'} src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" />
              <Image
                width={200}
                src="https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg"
              />
            </Image.PreviewGroup>

          </Col>
        </Row>
      </Drawer>
      <Modal title="捐赠" visible={donationModal} onOk={donationOk} width={300} onCancel={() => { setDonationModal(false) }}>

        {
          currentOrg?.goodsneed.map((item, index) => {
            return (
              <Row align="middle" justify="space-between" style={{width:'80%',margin: '0 auto',marginBottom:10}}>
                <Col>
                  <Tag color="green">{item.goodsname}</Tag>
                </Col>
                <Col>
                  <InputNumber min={0} max={100} controls={false}
                    onChange={(value) => {
                      if ( donationRs.goods.length==0 ) {
                        donationRs.goods.push({ "goodsname": item.goodsname, "goodsnum": value.eventPhase })
                      }
                        for (let i = 0; i < donationRs.goods.length; i++) {
                          if (donationRs.goods[i].goodsname ==item.goodsname) {
                            donationRs.goods[i].goodsnum = value;
                          }else{
                            if (i ==donationRs.goods.length-1) {
                              donationRs.goods.push({ "goodsname": item.goodsname, "goodsnum": value })
                            }
                          }
                        }
                    }
                    }
                  />
                </Col>
              </Row>

            )
          })
        }

      </Modal>
    </div>
  )
}
